import glUtils from "../utils/glUtils";
import filtUtils from "../utils/filtUtils";

export default {

    gl: null,
    vao: -1,
    vbo: -1,
    program:null,
    bInited:false,

    // handle  glsl layout 里面指定
    vPosition:0,

    init(gl) {
        this.gl = gl;

        let self = this;
        filtUtils.async_loadFiles([
            'shaders/test_vs.glsl',
            'shaders/test_fs.glsl',
        ]).then((lstShader)=>{
            // console.log('vs:',lstShader[0]);
            // console.log('fs:',lstShader[1]);
            self.onInit(lstShader[0],lstShader[1]);
        }).catch(()=>{
            console.error('load shader error!');
        });
    },

    onInit(vs,fs){
        this.bInited = true;

        const vertices = [
            -0.9, -0.9,
            0.85, -0.9,
            -0.9, 0.85,

            0.9, -0.85,
            0.9, 0.9,
            -0.85, 0.9
        ];
        let gl = this.gl;

        this.program = glUtils.createProgram(gl,vs,fs);

        this.vao = gl.createVertexArray();
        gl.bindVertexArray(this.vao);

        this.vbo = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER,this.vbo);
        gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(vertices),gl.STATIC_DRAW);

        gl.vertexAttribPointer(this.vPosition,2,gl.FLOAT,false,0,0);
        gl.enableVertexAttribArray(this.vPosition);

        gl.bindVertexArray(null);
    },

    render(){

        if(!this.bInited){
            return;
        }

        let gl = this.gl;

        gl.useProgram(this.program);
        gl.bindVertexArray(this.vao);
        gl.drawArrays(gl.TRIANGLES,0,6);
        gl.bindVertexArray(null);
    }

}